﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using WinnerCMS.Common;using WinnerCMS.CacheStorager;
namespace WinnerCMS.WebFactory
{
    /// <summary>
    /// 网页缓存适配器
    /// </summary>
    public class WebOutputCacheProvider : OutputCacheProvider
    {
        private const string KEY_PREFIX = "__outputCache_";
        /// <summary>
        /// 如果缓存设定的时间超过此值则缓存到文件中，否则在HttpRuntime.Cache中做缓存
        /// </summary>
        [XmlAttribute("memoryCacheLimit")]
        public TimeSpan MemoryCacheLimit { get; set; }


        /// <summary>
        /// 文件缓存的根目录，可以指定任何可访问目录
        /// </summary>
        [XmlAttribute("fileCacheRoot")]
        public string FileCacheRoot { get; set; }

        /// <summary> 
        /// 初始化WebOutputCacheProvider，读取配置文件中配置的MemoryCacheLimit和FileCacheRoot的值 
        /// </summary> 
        /// <param name="name">provider名字</param> 
        /// <param name="config">配置</param> 
        public override void Initialize(string name, NameValueCollection config)
        {
            string memoryLimit = config["memoryCacheLimit"];
            if (memoryLimit == null)
            {
                MemoryCacheLimit = new TimeSpan(0, 30, 0);
            }
            else
            {
                MemoryCacheLimit = TimeSpan.Parse(memoryLimit);
            }

            string fileCacheRoot = config["fileCacheRoot"];
            if (string.IsNullOrEmpty(fileCacheRoot))
            {
                fileCacheRoot = AppDomain.CurrentDomain.BaseDirectory + "cache\\";
            }
            this.FileCacheRoot = fileCacheRoot;
            base.Initialize(name, config);
        }

        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            CMSCaches.Context.Add(key, entry, 3600);
            return entry;
        }

        public override object Get(string key)
        {
            return CMSCaches.Context.Get<object>(key);
        }

        public override void Remove(string key)
        {
            CMSCaches.Context.Remove(key);
        }

        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            CMSCaches.Context.Add(key, entry, 3600);
        }
    }
}
